package android.slc.user.ui;

import android.app.Application;
import android.os.Bundle;
import android.slc.appbase.api.slc.callback.SlcObserver;
import android.slc.appbase.utils.ClickCountProxy;
import android.slc.appbase.vm.AppBaseViewModel;
import android.slc.appbase.vm.GlobalDataVm;
import android.slc.extras.main_biz.config.ConstantsMainBiz;
import android.slc.extras.system.config.ConstantsSystem;
import android.slc.extras.user.config.ConstantsUser;
import android.slc.extras.user.entity.UserInfo;
import android.slc.extras.user.repository.local.UserSp;
import android.slc.extras.user.repository.remote.UserServiceRepository;
import android.slc.or.SlcCallbackConfig;
import android.slc.user.R;

import androidx.annotation.NonNull;
import androidx.databinding.Observable;
import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;

/**
 * @author slc
 * @date 2020-06-19 10:00
 */
public class LoginVm extends AppBaseViewModel {
    private boolean isOnlyFinish = false;
    public final ObservableBoolean isAutoLogin = new ObservableBoolean(UserSp.isAutoLogin());
    public final ObservableBoolean isSavePassword = new ObservableBoolean(UserSp.isSavePassword());
    public final ObservableField<String> userAccountOf = new ObservableField<>();
    public final ObservableField<String> userPasswordOf = new ObservableField<>();

    public LoginVm(@NonNull Application application) {
        super(application);
    }

    public void init(Bundle bundle) {
        if (bundle != null) {
            isOnlyFinish = bundle.getBoolean(ConstantsUser.Key.KEY_LOGIN_ONLY_FINISH, false);
        }
        isAutoLogin.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (isAutoLogin.get()) {
                    isSavePassword.set(true);
                }
            }
        });
        userAccountOf.set(UserSp.getCurrentUser());
        if (isSavePassword.get()) {
            userPasswordOf.set(UserSp.getCurrentUserPassword());
            if (isAutoLogin.get()) {
                login();
            }
        }
    }

    public void login() {
        if (StringUtils.isEmpty(userAccountOf.get())) {
            ToastUtils.showShort(R.string.user_label_input_account);
            return;
        }
        if (StringUtils.isEmpty(userPasswordOf.get())) {
            ToastUtils.showShort(R.string.user_label_input_password);
            return;
        }
        UserServiceRepository.login(userAccountOf.get(), userPasswordOf.get())
                .to(bindToLifecycle())
                .subscribe(new SlcObserver<UserInfo>(SlcCallbackConfig.newBuilder()
                        .setDialogMsg(R.string.user_label_logging_in)
                        .setToastRes(R.string.user_toast_login_login_failed).build()) {
                    @Override
                    public void onSucceed(UserInfo data) {
                        UserSp.setAutoLogin(isAutoLogin.get());
                        UserSp.setSavePassword(isSavePassword.get());
                        UserSp.saveCurrentUserPassword(userPasswordOf.get());
                        UserSp.saveCurrentUser(data.getUserName());
                        UserSp.saveCurrentUserId(data.getId());
                        GlobalDataVm.getInstance().userVmBox.userOf.set(data);
                        ToastUtils.showShort(R.string.user_toast_login_login_successful);
                        if (!isOnlyFinish) {
                            showMain();
                        }
                        finish();
                    }

                    @Override
                    public void onFailed(int errorCode, String errorMessage) {
                    }
                });
    }

    public void showMain() {
        startActivityByARouterOf.setValue(ARouter.getInstance().build(ConstantsMainBiz.Path.PATH_MAIN_BIZ_MAIN_ACTIVITY));
    }


    private ClickCountProxy clickCountProxy;

    public void startConfigApi() {
        if (this.clickCountProxy == null) {
            this.clickCountProxy = new ClickCountProxy();
            this.clickCountProxy.setOnExecuteListener(new ClickCountProxy.OnExecuteListener() {
                @Override
                public void onExecute() {
                    //启动
                    startActivityByARouterOf.setValue(ARouter.getInstance().build(ConstantsSystem.Path.PATH_API_CONFIG_ACTIVITY));
                }
            });
        }
        this.clickCountProxy.call();
    }
}
